# encoding:utf8

import os
import sys
import shutil
import json
import time
import tarfile
from argparse import ArgumentParser
from mgamedev.py_lib import remote

""" 发布线上包 """


PATH_TEMPLATE = "TEMPLATE_DIR_"
XLUNZIP_TAG_F = "result.txt"


def filter_f(filename):
    if not filename.endswith(".lua")\
            and not filename.startswith("."):
        return True


class RelPackage:

    @staticmethod
    def xl_unziptag():
        with open(XLUNZIP_TAG_F, "wb") as fp:
            fp.write(bytes(str(time.time()).encode("utf8")) + b",")
            return fp

    @staticmethod
    def encode_package(ppath, rpath):
        XXTEA_SIGN = "mXjv7U5dUl1aMTVV_xianlai"
        XXTEA_KEY = "SQLLiteData"
        cmd_cocos = "cocos luacompile -s {frompath} -d {topath} -e -k {sign} -b {key} --disable-compile".format(
                    frompath=ppath,
                    topath=rpath,
                    sign=XXTEA_SIGN,
                    key=XXTEA_KEY
        )
        os.system(cmd_cocos)
        fileobj = None
        for root, dirs, files in os.walk(ppath):
            for filename in files:
                fileobj = os.path.join(root, filename)
                if filter_f(filename) and os.path.isfile(fileobj):
                    os.renames(fileobj, fileobj.replace(ppath, rpath))

    @classmethod
    def upload_remote(cls, localf):
        host = cls._cfg.get("host")
        pwd = cls._cfg.get("pwd")
        usr = cls._cfg.get("usr")
        path = cls._cfg.get("path")
        con = remote.RemoteCtrl(host, usr=usr, pwd=pwd)
        con.ftp_upload(localf, os.path.join(path, "autoUnZip.tgz"))
        RelPackage.xl_unziptag()
        con.ftp_upload(XLUNZIP_TAG_F,
                       os.path.join(path, XLUNZIP_TAG_F))
        con.close()

    @classmethod
    def execute(cls, pname, remotejson):
        cls._name = pname
        with open(remotejson) as fp:
            cfg = json.load(fp)
            cls._cfg = cfg
            print("server conf", json.dumps(cfg))
        # get zip
        os.system("ccpm install %s -o 1" % pname)
        n_path = os.getcwd()
        r_path = os.path.join(n_path, pname)
        # unzip
        f_zip = pname + ".zip"
        os.system("unzip -q  ./%s -d %s" % (f_zip, r_path))


        # generate zip
        f_tgz = pname + ".tgz"
        out = tarfile.TarFile.open(f_tgz, "w")
        out.add(r_path, pname, True)
        out.close()
        cls.upload_remote(f_tgz)

        # del
        shutil.rmtree(r_path)
        os.remove(f_zip)
        os.remove(f_tgz)
        os.remove(XLUNZIP_TAG_F)


if __name__ == "__main__":
    parser = ArgumentParser("Tool for release ccpm's package.")
    parser.add_argument("-p", dest="packagename",
                        help="ccpm's pakcage name")
    parser.add_argument("-s", dest="server_json",
                        help="the json config of the ftp server")
    args = parser.parse_args()
    if args.packagename and args.server_json:
        RelPackage().execute(args.packagename, args.server_json)
    else:
        parser.print_help()
